package cn.hzu580.dao.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import cn.hzu580.dao.BaseDAO;

@Repository("DAO")
public class BaseDAOImpl implements BaseDAO {

	@Resource
	private SessionFactory sessionFactory;
	

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public void insert(Object pEntity) {
		sessionFactory.getCurrentSession().save(pEntity);
	}

	@Override
	public void delete(Object pEntity) {
		sessionFactory.getCurrentSession().delete(pEntity);
	}

	@Override
	public void update(Object pEntity) {
		sessionFactory.getCurrentSession().update(pEntity);
	}


	@Override
	public Object get(Class<?> clazz, Serializable pSerializable) {
		Object _Entity = sessionFactory.getCurrentSession().get(clazz, pSerializable);
		return _Entity;
	}


	@Override
	public List<?> exeQuery(String prepareHQL, Map<String, Object> parameters) {
		return exeQuery(prepareHQL, parameters, 0, 0);
	}

	
	@Override
	public List<?> exeQuery(String prepareHQL, Map<String, Object> parameters, int firstResult, int maxResult) {
		Query query =  sessionFactory.getCurrentSession().createQuery(prepareHQL);
		if(maxResult !=0){
			query.setFirstResult(firstResult).setMaxResults(maxResult);
		}
		if(parameters != null){
			for (Entry<String, Object> parameter : parameters.entrySet()) {
				for (String s : query.getNamedParameters()) {
					if(parameter.getKey().equals(s)){
						query.setParameter(s, parameter.getValue());
						break;
					}
				}
			}
		}
		List<?> _List = query.list();
		return _List;
	}
	
	
	@Override
	public int exeUpdate(String prepareHQL, Map<String, Object> parameters) {
		Query query =  sessionFactory.getCurrentSession().createQuery(prepareHQL);
		if(parameters != null){
			for (Entry<String, Object> parameter : parameters.entrySet()) {
				for (String s : query.getNamedParameters()) {
					if(parameter.getKey().equals(s)){
						query.setParameter(s, parameter.getValue());
						break;
					}
				}
			}
		}
		int _Result = query.executeUpdate();
		return _Result;
	}

	
	@Override
	public Criteria createQBC(Class<?> clazz) {
		return sessionFactory.getCurrentSession().createCriteria(clazz);
	}
}
